package com.example.jdimust.register;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.example.jdimust.main.ui.Dataquery.DataqueryFragment.client;

/**
 * Author: MaZongyang
 * Date: 2021/5/21/0021 0:25
 * Description:网络请求类
 */
public class NetworkRequest {

    /**
     * @param command    请求命令
     * @param querid     查询ID
     * @param ledgerHash 账本Hash(非必须)
     * @return
     */
    public static String getaccount(String command, String querid, String ledgerHash) {
        String reqreturn = null;
        String allaccresult = null;
        Response response = null;
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
        Request request = new Request.Builder()
                .url("https://hzy.graduationproject.xyz" + command + querid)//请求接口。如果需要传参拼接到接口后面。
                .build();//创建Request 对象
        try {
            response = client.newCall(request).execute();//得到Response 对象
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response.isSuccessful()) {
            try {
                reqreturn = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        response.close();
//        System.out.println(reqreturn);
        return reqreturn;
    }

    public static String postaccount(String command, String tojson, MediaType header) throws IOException {
        RequestBody body = RequestBody.create(header, tojson);
        Request request = new Request.Builder()
                .url("https://hzy.graduationproject.xyz" + command)
                .post(body)
                .addHeader("Connection", "close")
                .build();
        Response response = client.newCall(request).execute();
        String rejson = null;
        if (response.isSuccessful()) {
            rejson = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
        return rejson;
    }
}
